/*
 * Copyright (c) 2008, intarsys consulting GmbH
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Public License as published by the 
 * Free Software Foundation; either version 3 of the License, 
 * or (at your option) any later version.
 * <p/>
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * 
 */
package de.intarsys.pdf.example.rendering.awt;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import de.intarsys.cwt.awt.environment.CwtAwtGraphicsContext;
import de.intarsys.cwt.environment.IGraphicsContext;
import de.intarsys.pdf.content.CSContent;
import de.intarsys.pdf.example.common.CommonJPodRendererExample;
import de.intarsys.pdf.pd.PDPage;
import de.intarsys.pdf.pd.PDPageTree;
import de.intarsys.pdf.platform.cwt.rendering.CSPlatformRenderer;

/**
 * Render the document pages to a {@link BufferedImage}.
 */
public class RenderDoc extends CommonJPodRendererExample {

	public static int SCALE = 2;

	public static void main(String[] args) {
		RenderDoc client = new RenderDoc();
		try {
			client.run(args);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected BufferedImage renderPage(PDPage page) {
		Rectangle2D rect = page.getCropBox().toNormalizedRectangle();
		BufferedImage image = null;
		IGraphicsContext graphics = null;
		try {
			image = new BufferedImage((int) rect.getWidth() * SCALE, (int) rect
					.getHeight()
					* SCALE, BufferedImage.TYPE_INT_RGB);
			Graphics2D g2 = (Graphics2D) image.getGraphics();
			graphics = new CwtAwtGraphicsContext(g2);
			// setup user space
			AffineTransform imgTransform = graphics.getTransform();
			imgTransform.scale(SCALE, -SCALE);
			imgTransform.translate(-rect.getMinX(), -rect.getMaxY());
			graphics.setTransform(imgTransform);
			graphics.setBackgroundColor(Color.WHITE);
			graphics.fill(rect);
			CSContent content = page.getContentStream();
			if (content != null) {
				CSPlatformRenderer renderer = new CSPlatformRenderer(null,
						graphics);
				renderer.process(content, page.getResources());
			}
			return image;
		} finally {
			if (graphics != null) {
				graphics.dispose();
			}
		}
	}

	@SuppressWarnings("rawtypes")
	protected void renderPages(String filename) {
		//
		ImageWriter writer = null;
		Iterator iter = ImageIO.getImageWritersByFormatName("png");
		if (iter.hasNext()) {
			writer = (ImageWriter) iter.next();
		}
		//
		PDPageTree pages = getDoc().getPageTree();
		PDPage page = pages.getFirstPage();
		int i = 0;
		while (page != null) {
			BufferedImage image = renderPage(page);
			File outputFile = new File(filename + "." + i + ".png");
			ImageOutputStream ios = null;
			try {
				ios = ImageIO.createImageOutputStream(outputFile);
				writer.setOutput(ios);
				writer.write(null, new IIOImage(image, null, null), null);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (ios != null) {
					try {
						ios.flush();
					} catch (IOException e) {
					}
					try {
						ios.close();
					} catch (IOException e) {
					}
				}
				writer.reset();
			}
			System.out.print(".");
			i++;
			if (i % 10 == 0) {
				System.out.println();
			}
			page = page.getNextPage();
		}
		//
		writer.dispose();
	}

	public void run(String[] args) throws Exception {
		if (args.length < 1) {
			usage();
			return;
		}
		try {
			String inputFileName = args[0];
			open(inputFileName);
			renderPages(inputFileName);
		} finally {
			close();
		}
	}

	/**
	 * Help the user.
	 */
	public void usage() {
		System.out.println("usage: java.exe " + getClass().getName() //$NON-NLS-1$
				+ " <input-pdf>"); //$NON-NLS-1$
	}
}
